package me.cxlr.qinlauncher2.adapter.drawer;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.content.res.AppCompatResources;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.List;
import java.util.Objects;

import me.cxlr.qinlauncher2.R;
import me.cxlr.qinlauncher2.adapter.NeedFlushCallBack;
import me.cxlr.qinlauncher2.constants.Constants;
import me.cxlr.qinlauncher2.manager.IconManager;
import me.cxlr.qinlauncher2.manager.SoftwareManager;
import me.cxlr.qinlauncher2.model.App;
import me.cxlr.qinlauncher2.model.AppAndFolder;
import me.cxlr.qinlauncher2.model.Folder;
import me.cxlr.qinlauncher2.util.DisplayUtil;
import me.cxlr.qinlauncher2.util.SharedPreferencesUtil;
import me.cxlr.qinlauncher2.util.ToastUtil;
import me.cxlr.qinlauncher2.view.drawer.DrawerFragment;
import me.cxlr.qinlauncher2.viewmodel.drawer.DrawerViewModel;

/**
 * @author 酷安用户:山轮纸
 */
public class DrawerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final Activity activity;
    private final Context context;
    private final DrawerFragment fragment;
    private final DrawerViewModel viewModel;
    private final List<AppAndFolder> appAndFolderList;
    private final int appDrawerStyle;

    public DrawerAdapter(DrawerFragment fragment, DrawerViewModel viewModel, List<AppAndFolder> appAndFolderList, int appDrawerStyle) {
        this.activity = fragment.requireActivity();
        this.context = fragment.requireContext();
        this.fragment = fragment;
        this.viewModel = viewModel;
        this.appAndFolderList = appAndFolderList;
        this.appDrawerStyle = appDrawerStyle;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view;
        // 宫格布局
        if (viewType == Constants.APP_DRAWER_STYLE_GRID) {
            view = LayoutInflater.from(context).inflate(R.layout.item_drawer_grid, parent, false);
            return new AppDrawerGridViewHolder(activity, context, fragment, view, viewModel);
        }
        // 列表布局
        else {
            view = LayoutInflater.from(context).inflate(R.layout.item_drawer_linear, parent, false);
            return new AppDrawerLinearViewHolder(activity, context, fragment, view, viewModel);
        }
    }

    @Override
    @SuppressLint("UseCompatLoadingForDrawables")
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        int type = getItemViewType(position);
        // 宫格布局
        if (type == Constants.APP_DRAWER_STYLE_GRID) {
            AppDrawerGridViewHolder viewHolder = (AppDrawerGridViewHolder) holder;
            View view = viewHolder.view;
            viewHolder.appAndFolder = appAndFolderList.get(position);

            // app
            if (viewHolder.appAndFolder.isApp()) {
                viewHolder.llcItem.setOnClickListener(v -> SoftwareManager.getInstance().openApplication(activity, context, viewHolder.appAndFolder.getApp().getPackageName(), viewHolder.appAndFolder.getApp().getClazzName()));
                viewHolder.tvLabel.setText(viewHolder.appAndFolder.getApp().getLabel());
                viewHolder.setIconAndLabelSize(context);

                Drawable icon = IconManager.getInstance().getApplicationIcon(viewHolder.appAndFolder.getApp().getPackageName(), viewHolder.appAndFolder.getApp().getClazzName());
                viewHolder.imgIcon.setImageDrawable(icon);
            }
            // 文件夹
            else {
                viewHolder.llcItem.setOnClickListener(v -> viewHolder.openFolder());
                viewHolder.tvLabel.setText(viewHolder.appAndFolder.getFolder().getFolderName());
                viewHolder.setFolderIconAndSize(context);

                Drawable icon = context.getResources().getDrawable(R.drawable.icon_folder, null);
                viewHolder.imgIcon.setImageDrawable(icon);
            }
        }
        // 列表布局
        else if (type == Constants.APP_DRAWER_STYLE_LINEAR) {
            AppDrawerLinearViewHolder viewHolder = (AppDrawerLinearViewHolder) holder;
            View view = viewHolder.view;
            viewHolder.appAndFolder = appAndFolderList.get(position);

            // app
            if (viewHolder.appAndFolder.isApp()) {
                viewHolder.llcItem.setOnClickListener(v -> SoftwareManager.getInstance().openApplication(activity, context, viewHolder.appAndFolder.getApp().getPackageName(), viewHolder.appAndFolder.getApp().getClazzName()));
                viewHolder.tvLabel.setText(viewHolder.appAndFolder.getApp().getLabel());
                viewHolder.setIconAndLabelSize(context);

                Drawable icon = IconManager.getInstance().getApplicationIcon(viewHolder.appAndFolder.getApp().getPackageName(), viewHolder.appAndFolder.getApp().getClazzName());
                viewHolder.imgIcon.setImageDrawable(icon);
            }
            // 文件夹
            else {
                viewHolder.llcItem.setOnClickListener(v -> viewHolder.openFolder());
                viewHolder.tvLabel.setText(viewHolder.appAndFolder.getFolder().getFolderName());
                viewHolder.setFolderIconAndSize(context);

                Drawable icon = context.getResources().getDrawable(R.drawable.icon_folder, null);
                viewHolder.imgIcon.setImageDrawable(icon);
            }
        }
    }

    @Override
    public int getItemCount() {
        return appAndFolderList.size();
    }

    @Override
    public int getItemViewType(int position) {
        // 宫格布局
        if (appDrawerStyle == Constants.APP_DRAWER_STYLE_GRID) {
            return 0;
        }
        // 列表布局
        else {
            return 1;
        }
    }

    /**
     * 应用抽屉的列表布局
     */
    public static class AppDrawerLinearViewHolder extends RecyclerView.ViewHolder implements NeedFlushCallBack {
        public final View view;
        public final Activity activity;
        public final Context context;
        public final DrawerFragment fragment;
        public final DrawerViewModel viewModel;
        public final LinearLayoutCompat llcItem;
        public final AppCompatImageView imgIcon;
        public final AppCompatTextView tvLabel;

        public AppAndFolder appAndFolder;

        public AppDrawerLinearViewHolder(Activity activity, Context context, DrawerFragment fragment, View view, DrawerViewModel viewModel) {
            super(view);
            this.view = view;
            this.activity = activity;
            this.context = context;
            this.fragment = fragment;
            this.viewModel = viewModel;
            llcItem = view.findViewById(R.id.iadl_ll_item);
            imgIcon = view.findViewById(R.id.iadl_img_icon);
            tvLabel = view.findViewById(R.id.iadl_tv_label);

            this.setMenu();
        }

        /**
         * 设置App的图标和标题大小
         *
         * @param context 上下文
         */
        public void setIconAndLabelSize(Context context) {
            float size = Float.parseFloat(SharedPreferencesUtil.getInstance().getString("app_icon_size", "60"));
            float labelTextSize = Float.parseFloat(SharedPreferencesUtil.getInstance().getString("app_label_size", "20"));

            ViewGroup.LayoutParams params = imgIcon.getLayoutParams();
            params.height = DisplayUtil.dpToPx(context, size);
            params.width = DisplayUtil.dpToPx(context, size);
            imgIcon.setLayoutParams(params);

            ViewGroup.LayoutParams params2 = tvLabel.getLayoutParams();
            params.height = DisplayUtil.dpToPx(context, size);
            tvLabel.setLayoutParams(params2);

            boolean showAppLabelFlag = SharedPreferencesUtil.getInstance().getBoolean("show_app_label", true);
            if (showAppLabelFlag) {
                tvLabel.setTextSize(labelTextSize);
            } else {
                tvLabel.setTextSize(0);
            }
        }

        /**
         * 设置文件夹的图标和标题大小
         *
         * @param context 上下文
         */
        public void setFolderIconAndSize(Context context) {
            Drawable icon = AppCompatResources.getDrawable(context, R.drawable.icon_folder);
            imgIcon.setImageDrawable(icon);

            float size = Float.parseFloat(SharedPreferencesUtil.getInstance().getString("app_icon_size", "66"));
            float labelTextSize = Float.parseFloat(SharedPreferencesUtil.getInstance().getString("app_label_size", "20"));

            ViewGroup.LayoutParams params = imgIcon.getLayoutParams();
            params.height = DisplayUtil.dpToPx(context, size);
            params.width = DisplayUtil.dpToPx(context, size);
            imgIcon.setLayoutParams(params);

            ViewGroup.LayoutParams params2 = tvLabel.getLayoutParams();
            params.height = DisplayUtil.dpToPx(context, size);
            tvLabel.setLayoutParams(params2);
            boolean showAppLabelFlag = SharedPreferencesUtil.getInstance().getBoolean("show_folder_label", true);
            if (showAppLabelFlag) {
                tvLabel.setTextSize(labelTextSize);
            } else {
                tvLabel.setTextSize(0);
            }
        }

        /**
         * 设置App和文件夹的菜单
         */
        private void setMenu() {
            this.view.setOnCreateContextMenuListener((menu, v, menuInfo) -> {
                // app
                if (appAndFolder.isApp()) {
                    menu.setHeaderTitle(appAndFolder.getApp().getLabel());

                    menu.add(0, 0, Menu.NONE, "打开");
                    MenuItem item1 = menu.findItem(0);
                    item1.setOnMenuItemClickListener(item -> {
                        SoftwareManager.getInstance().openApplication(activity, view.getContext(), appAndFolder.getApp().getPackageName(), appAndFolder.getApp().getClazzName());
                        return false;
                    });

                    menu.add(0, 1, Menu.NONE, "卸载");
                    MenuItem item2 = menu.findItem(1);
                    item2.setOnMenuItemClickListener(item -> {
                        SoftwareManager.getInstance().uninstallApplication(activity, view.getContext(), appAndFolder.getApp().getPackageName());
                        return false;
                    });

                    boolean showHiddenAppMenuFlag = SharedPreferencesUtil.getInstance().getBoolean("app_drawer_hide_show", true);
                    if (showHiddenAppMenuFlag) {
                        menu.add(0, 2, Menu.NONE, "隐藏应用");
                        MenuItem item3 = menu.findItem(2);
                        item3.setOnMenuItemClickListener(item -> {
                            dialogHiddenApp(appAndFolder.getApp());
                            return false;
                        });
                    }

                    menu.add(0, 3, Menu.NONE, "应用信息");
                    MenuItem item4 = menu.findItem(3);
                    item4.setOnMenuItemClickListener(item -> {
                        SoftwareManager.getInstance().openApplicationMessage(activity, view.getContext(), appAndFolder.getApp().getPackageName());
                        return false;
                    });

                    menu.add(0, 4, Menu.NONE, "移入文件夹");
                    MenuItem item5 = menu.findItem(4);
                    item5.setOnMenuItemClickListener(item -> {
                        removeAppToFolder(appAndFolder.getApp());
                        return false;
                    });
                } else if (appAndFolder.isFolder()) {
                    menu.setHeaderTitle(appAndFolder.getFolder().getFolderName());
                    menu.add(0, 0, Menu.NONE, "打开");
                    MenuItem item1 = menu.findItem(0);
                    item1.setOnMenuItemClickListener(item -> {
                        openFolder();
                        return false;
                    });

                    menu.add(0, 1, Menu.NONE, "删除");
                    MenuItem item2 = menu.findItem(1);
                    item2.setOnMenuItemClickListener(item -> {
                        dialogFolderDelete();
                        return false;
                    });
                }
            });
        }

        /**
         * 隐藏应用
         *
         * @param hiddenApp App
         */
        private void dialogHiddenApp(App hiddenApp) {
            AlertDialog alertDialog = new AlertDialog.Builder(view.getContext())
                    .setTitle("隐藏应用")
                    .setMessage("是否隐藏应用?隐藏后只可在应用抽屉设置中查看")
                    .setNegativeButton("是", (dialog, which) -> {
                        viewModel.hiddenApp(hiddenApp);
                        fragment.flush();
                        dialog.dismiss();
                    })
                    .setPositiveButton("关闭", (dialog, which) -> dialog.dismiss())
                    .create();
            alertDialog.show();
        }

        /**
         * 移动App到文件夹
         *
         * @param app App
         */
        private void removeAppToFolder(App app) {
            List<Folder> folderList = viewModel.getFolderList();
            // 选择文件夹
            if (folderList.size() > 0) {
                String[] folderName = new String[folderList.size()];
                for (int i = 0; i < folderList.size(); i++) {
                    folderName[i] = folderList.get(i).getFolderName();
                }
                AlertDialog alertDialog = new AlertDialog.Builder(view.getContext())
                        .setTitle("选择文件夹")
                        .setItems(folderName, (dialog, which) -> {
                            String str = viewModel.chosenIntoFolder(folderList.get(which), app);
                            ToastUtil.show(view.getContext(), str, ToastUtil.LENGTH_LONG);
                            fragment.flush();
                            dialog.dismiss();
                        })
                        .setPositiveButton("关闭", (dialog, which) -> dialog.dismiss())
                        .create();
                alertDialog.show();
            }
            // 无文件夹
            else {
                ToastUtil.show(fragment.requireContext(), "无文件夹,请先创建文件夹", ToastUtil.LENGTH_LONG);
            }
        }

        private FolderAdapter folderAdapter;
        private RecyclerView rvFolder;
        private PopupWindow pwFolder;
        private LinearLayoutCompat llRoot;
        private LinearLayoutCompat llLabel;
        private AppCompatTextView tvFolderLabel;
        private LinearLayoutCompat llFolder;
        private AppCompatTextView tvNoApp;
        private AppCompatEditText etFolderName;

        /**
         * 开启文件夹
         */
        private void openFolder() {
            View view = activity.getLayoutInflater().inflate(R.layout.dialog_show_folder_new, null);
            pwFolder = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            llRoot = view.findViewById(R.id.dsfn_ll_root);
            llLabel = view.findViewById(R.id.dsfn_ll_label);
            tvFolderLabel = view.findViewById(R.id.dsfn_tv_label);
            llFolder = view.findViewById(R.id.dsfn_ll_folder);
            tvNoApp = view.findViewById(R.id.dsfn_tv_no_app);
            rvFolder = view.findViewById(R.id.dsfn_rv_folder);
            initAppInFolder();
            int appSize = viewModel.getAppInFolderList(appAndFolder.getFolder()).size();
            if (appSize == 0) {
                setFolderStyle();
            }
            pwFolder.showAsDropDown(view);
        }

        /**
         * 设置文件夹没有App时的样式
         */
        private void setFolderStyle() {
            tvNoApp.setVisibility(View.VISIBLE);
            rvFolder.setVisibility(View.GONE);
        }

        /**
         * 加载文件夹内的App
         */
        private void initAppInFolder() {
            tvNoApp.setVisibility(View.GONE);
            rvFolder.setVisibility(View.VISIBLE);
            llRoot.setOnClickListener(v -> pwFolder.dismiss());
            tvFolderLabel.setText(appAndFolder.getFolder().getFolderName());
            tvFolderLabel.setOnClickListener(v -> dialogFolderEdit());
            List<App> appInFolderList = viewModel.getAppInFolderList(appAndFolder.getFolder());
            folderAdapter = new FolderAdapter(activity, context, appInFolderList);
            folderAdapter.setFlush(this);
            rvFolder.setLayoutManager(new GridLayoutManager(context, 3));
            rvFolder.setAdapter(folderAdapter);
        }

        /**
         * 编辑文件夹名称
         */
        private void dialogFolderEdit() {
            View view = fragment.requireActivity().getLayoutInflater().inflate(R.layout.dialog_create_folder, null);
            etFolderName = view.findViewById(R.id.dcf_et_folder_name);
            AlertDialog dialogCreate = new AlertDialog.Builder(fragment.requireContext())
                    .setPositiveButton("保存", (dialog, which) -> {
                        if ("".equals(Objects.requireNonNull(etFolderName.getText()).toString())) {
                            ToastUtil.show(fragment.requireContext(), "请输入文件夹名称", ToastUtil.LENGTH_LONG);
                        } else {
                            String newFolderName = etFolderName.getText().toString();
                            viewModel.updateAppById(appAndFolder.getFolder(), newFolderName);
                            tvLabel.setText(newFolderName);
                            tvFolderLabel.setText(newFolderName);
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                    .setTitle("修改文件夹标题")
                    .setView(view)
                    .setCancelable(true)
                    .create();
            dialogCreate.show();
        }

        /**
         * 删除文件夹
         */
        private void dialogFolderDelete() {
            etFolderName = view.findViewById(R.id.dcf_et_folder_name);
            AlertDialog dialogCreate = new AlertDialog.Builder(fragment.requireContext())
                    .setPositiveButton("是", (dialog, which) -> {
                        viewModel.deleteFolder(appAndFolder.getFolder());
                        fragment.flush();
                        dialog.dismiss();
                    })
                    .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                    .setTitle("删除文件夹")
                    .setMessage("删除文件夹:" + appAndFolder.getFolder().getFolderName() + "?")
                    .setCancelable(true)
                    .create();
            dialogCreate.show();
        }

        /**
         * 刷新文件夹
         */
        @Override
        public void flush(String action, App app, Folder folder) {
            switch (action) {
                case "up":
                case "down":
                    viewModel.appInFolderUpOrDown(action, app, folder);
                    break;
                case "out":
                    viewModel.appInFolderOut(app, folder);
                    fragment.flush();
                    ToastUtil.show(context, "移出文件夹,完成", ToastUtil.LENGTH_LONG);
                    break;
                default:
                    break;
            }
            List<App> appInFolderList = viewModel.getAppInFolderList(folder);
            folderAdapter = new FolderAdapter(activity, context, appInFolderList);
            folderAdapter.setFlush(this);
            rvFolder.setAdapter(folderAdapter);
            if (appInFolderList.size() == 0) {
                pwFolder.dismiss();
            }
        }

    }

    /**
     * 应用抽屉的宫格布局
     */
    public static class AppDrawerGridViewHolder extends RecyclerView.ViewHolder implements NeedFlushCallBack {
        public final View view;
        public final Activity activity;
        public final Context context;
        public final DrawerFragment fragment;
        public final DrawerViewModel viewModel;
        public final LinearLayoutCompat llcItem;
        public final AppCompatImageView imgIcon;
        public final AppCompatTextView tvLabel;

        public AppAndFolder appAndFolder;

        public AppDrawerGridViewHolder(Activity activity, Context context, DrawerFragment fragment, View view, DrawerViewModel viewModel) {
            super(view);
            this.view = view;
            this.activity = activity;
            this.context = context;
            this.fragment = fragment;
            this.viewModel = viewModel;
            llcItem = view.findViewById(R.id.iadg_ll_item);
            imgIcon = view.findViewById(R.id.iadg_img_icon);
            tvLabel = view.findViewById(R.id.iadg_tv_label);

            this.setMenu();
        }

        /**
         * 设置App的图标和标题大小
         *
         * @param context 上下文
         */
        public void setIconAndLabelSize(Context context) {
            float size = Float.parseFloat(SharedPreferencesUtil.getInstance().getString("app_icon_size", "60"));
            float labelTextSize = Float.parseFloat(SharedPreferencesUtil.getInstance().getString("app_label_size", "20"));

            ViewGroup.LayoutParams params = imgIcon.getLayoutParams();
            params.height = DisplayUtil.dpToPx(context, size);
            params.width = DisplayUtil.dpToPx(context, size);
            imgIcon.setLayoutParams(params);

            boolean showAppLabelFlag = SharedPreferencesUtil.getInstance().getBoolean("show_app_label", true);
            if (showAppLabelFlag) {
                tvLabel.setTextSize(labelTextSize);
            } else {
                tvLabel.setTextSize(0);
            }
        }

        /**
         * 设置文件夹的图标和标题大小
         *
         * @param context 上下文
         */
        public void setFolderIconAndSize(Context context) {
            Drawable icon = AppCompatResources.getDrawable(context, R.drawable.icon_folder);
            imgIcon.setImageDrawable(icon);

            float size = Float.parseFloat(SharedPreferencesUtil.getInstance().getString("app_icon_size", "66"));
            float labelTextSize = Float.parseFloat(SharedPreferencesUtil.getInstance().getString("app_label_size", "20"));

            ViewGroup.LayoutParams params = imgIcon.getLayoutParams();
            params.height = DisplayUtil.dpToPx(context, size);
            params.width = DisplayUtil.dpToPx(context, size);
            imgIcon.setLayoutParams(params);

            boolean showAppLabelFlag = SharedPreferencesUtil.getInstance().getBoolean("show_folder_label", true);
            if (showAppLabelFlag) {
                tvLabel.setTextSize(labelTextSize);
            } else {
                tvLabel.setTextSize(0);
            }
        }

        /**
         * 设置App和文件夹的菜单
         */
        private void setMenu() {
            this.view.setOnCreateContextMenuListener((menu, v, menuInfo) -> {
                // app
                if (appAndFolder.isApp()) {
                    menu.setHeaderTitle(appAndFolder.getApp().getLabel());
                    menu.add(0, 0, Menu.NONE, "打开");
                    MenuItem item1 = menu.findItem(0);
                    item1.setOnMenuItemClickListener(item -> {
                        SoftwareManager.getInstance().openApplication(activity, context, appAndFolder.getApp().getPackageName(), appAndFolder.getApp().getClazzName());
                        return false;
                    });

                    menu.add(0, 1, Menu.NONE, "卸载");
                    MenuItem item2 = menu.findItem(1);
                    item2.setOnMenuItemClickListener(item -> {
                        SoftwareManager.getInstance().uninstallApplication(activity, context, appAndFolder.getApp().getPackageName());
                        return false;
                    });

                    boolean showHiddenAppMenuFlag = SharedPreferencesUtil.getInstance().getBoolean("app_drawer_hide_show", true);
                    if (showHiddenAppMenuFlag) {
                        menu.add(0, 2, Menu.NONE, "隐藏应用");
                        MenuItem item3 = menu.findItem(2);
                        item3.setOnMenuItemClickListener(item -> {
                            dialogHiddenApp(appAndFolder.getApp());
                            return false;
                        });
                    }

                    menu.add(0, 3, Menu.NONE, "应用信息");
                    MenuItem item4 = menu.findItem(3);
                    item4.setOnMenuItemClickListener(item -> {
                        SoftwareManager.getInstance().openApplicationMessage(activity, context, appAndFolder.getApp().getPackageName());
                        return false;
                    });

                    menu.add(0, 4, Menu.NONE, "移入文件夹");
                    MenuItem item5 = menu.findItem(4);
                    item5.setOnMenuItemClickListener(item -> {
                        removeAppToFolder(appAndFolder.getApp());
                        return false;
                    });
                } else if (appAndFolder.isFolder()) {
                    menu.setHeaderTitle(appAndFolder.getFolder().getFolderName());
                    menu.add(0, 0, Menu.NONE, "打开");
                    MenuItem item1 = menu.findItem(0);
                    item1.setOnMenuItemClickListener(item -> {
                        openFolder();
                        return false;
                    });

                    menu.add(0, 1, Menu.NONE, "删除");
                    MenuItem item2 = menu.findItem(1);
                    item2.setOnMenuItemClickListener(item -> {
                        dialogFolderDelete();
                        return false;
                    });
                }
            });
        }

        /**
         * 隐藏应用
         *
         * @param hiddenApp App
         */
        private void dialogHiddenApp(App hiddenApp) {
            AlertDialog alertDialog = new AlertDialog.Builder(view.getContext())
                    .setTitle("隐藏应用")
                    .setMessage("是否隐藏应用?隐藏后只可在应用抽屉设置中查看")
                    .setNegativeButton("是", (dialog, which) -> {
                        viewModel.hiddenApp(hiddenApp);
                        fragment.flush();
                        dialog.dismiss();
                    })
                    .setPositiveButton("关闭", (dialog, which) -> dialog.dismiss())
                    .create();
            alertDialog.show();
        }

        /**
         * 移动App到文件夹
         *
         * @param app App
         */
        private void removeAppToFolder(App app) {
            List<Folder> folderList = viewModel.getFolderList();
            // 选择文件夹
            if (folderList.size() > 0) {
                String[] folderName = new String[folderList.size()];
                for (int i = 0; i < folderList.size(); i++) {
                    folderName[i] = folderList.get(i).getFolderName();
                }
                AlertDialog alertDialog = new AlertDialog.Builder(view.getContext())
                        .setTitle("选择文件夹")
                        .setItems(folderName, (dialog, which) -> {
                            String str = viewModel.chosenIntoFolder(folderList.get(which), app);
                            ToastUtil.show(view.getContext(), str, ToastUtil.LENGTH_LONG);
                            fragment.flush();
                            dialog.dismiss();
                        })
                        .setPositiveButton("关闭", (dialog, which) -> dialog.dismiss())
                        .create();
                alertDialog.show();
            }
            // 无文件夹
            else {
                ToastUtil.show(fragment.requireContext(), "无文件夹,请先创建文件夹", ToastUtil.LENGTH_LONG);
            }
        }

        private FolderAdapter folderAdapter;
        private RecyclerView rvFolder;
        private PopupWindow pwFolder;
        private LinearLayoutCompat llRoot;
        private LinearLayoutCompat llLabel;
        private AppCompatTextView tvFolderLabel;
        private LinearLayoutCompat llFolder;
        private AppCompatTextView tvNoApp;
        private AppCompatEditText etFolderName;

        /**
         * 开启文件夹
         */
        private void openFolder() {
            View view = activity.getLayoutInflater().inflate(R.layout.dialog_show_folder_new, null);
            pwFolder = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            llRoot = view.findViewById(R.id.dsfn_ll_root);
            llLabel = view.findViewById(R.id.dsfn_ll_label);
            tvFolderLabel = view.findViewById(R.id.dsfn_tv_label);
            llFolder = view.findViewById(R.id.dsfn_ll_folder);
            tvNoApp = view.findViewById(R.id.dsfn_tv_no_app);
            rvFolder = view.findViewById(R.id.dsfn_rv_folder);
            initAppInFolder();
            int appSize = viewModel.getAppInFolderList(appAndFolder.getFolder()).size();
            if (appSize == 0) {
                setFolderStyle();
            }
            pwFolder.showAsDropDown(view);
        }

        /**
         * 设置文件夹没有App时的样式
         */
        private void setFolderStyle() {
            tvNoApp.setVisibility(View.VISIBLE);
            rvFolder.setVisibility(View.GONE);
        }

        /**
         * 加载文件夹内的App
         */
        private void initAppInFolder() {
            tvNoApp.setVisibility(View.GONE);
            rvFolder.setVisibility(View.VISIBLE);
            llRoot.setOnClickListener(v -> pwFolder.dismiss());
            tvFolderLabel.setText(appAndFolder.getFolder().getFolderName());
            tvFolderLabel.setOnClickListener(v -> dialogFolderEdit());
            List<App> appInFolderList = viewModel.getAppInFolderList(appAndFolder.getFolder());
            folderAdapter = new FolderAdapter(activity, context, appInFolderList);
            folderAdapter.setFlush(this);
            rvFolder.setLayoutManager(new GridLayoutManager(context, 3));
            rvFolder.setAdapter(folderAdapter);
        }

        /**
         * 编辑文件夹名称
         */
        private void dialogFolderEdit() {
            View view = fragment.requireActivity().getLayoutInflater().inflate(R.layout.dialog_create_folder, null);
            etFolderName = view.findViewById(R.id.dcf_et_folder_name);
            AlertDialog dialogCreate = new AlertDialog.Builder(fragment.requireContext())
                    .setPositiveButton("保存", (dialog, which) -> {
                        if ("".equals(Objects.requireNonNull(etFolderName.getText()).toString())) {
                            ToastUtil.show(fragment.requireContext(), "请输入文件夹名称", ToastUtil.LENGTH_LONG);
                        } else {
                            String newFolderName = etFolderName.getText().toString();
                            viewModel.updateAppById(appAndFolder.getFolder(), newFolderName);
                            tvLabel.setText(newFolderName);
                            tvFolderLabel.setText(newFolderName);
                            dialog.dismiss();
                        }
                    })
                    .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                    .setTitle("修改文件夹标题")
                    .setView(view)
                    .setCancelable(true)
                    .create();
            dialogCreate.show();
        }

        /**
         * 删除文件夹
         */
        private void dialogFolderDelete() {
            etFolderName = view.findViewById(R.id.dcf_et_folder_name);
            AlertDialog dialogCreate = new AlertDialog.Builder(fragment.requireContext())
                    .setPositiveButton("是", (dialog, which) -> {
                        viewModel.deleteFolder(appAndFolder.getFolder());
                        fragment.flush();
                        dialog.dismiss();
                    })
                    .setNegativeButton("取消", (dialog, which) -> dialog.dismiss())
                    .setTitle("删除文件夹")
                    .setMessage("删除文件夹:" + appAndFolder.getFolder().getFolderName() + "?")
                    .setCancelable(true)
                    .create();
            dialogCreate.show();
        }

        /**
         * 刷新文件夹
         */
        @Override
        public void flush(String action, App app, Folder folder) {
            switch (action) {
                case "up":
                case "down":
                    viewModel.appInFolderUpOrDown(action, app, folder);
                    break;
                case "out":
                    viewModel.appInFolderOut(app, folder);
                    fragment.flush();
                    ToastUtil.show(context, "移出文件夹,完成", ToastUtil.LENGTH_LONG);
                    break;
                default:
                    break;
            }
            List<App> appInFolderList = viewModel.getAppInFolderList(folder);
            folderAdapter = new FolderAdapter(activity, context, appInFolderList);
            folderAdapter.setFlush(this);
            rvFolder.setAdapter(folderAdapter);
            if (appInFolderList.size() == 0) {
                pwFolder.dismiss();
            }
        }
    }
}
